package com.cloudlead.forwardAction.service.impl;

import com.cloudlead.commonData.service.*;
import com.cloudlead.commonData.vo.*;
import com.cloudlead.forwardAction.service.OrderInformationSaveSer;
import com.cloudlead.forwardService.vo.OrderInformationVo;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONObject;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by wyj on 2015/8/22.
 */
@Service
public class OrderInformationSaveSerImpl implements OrderInformationSaveSer {
    SimpleDateFormat ss= new SimpleDateFormat("yyyy-MM-dd HH:mm");
    @Autowired
    TbContainerInfoService tbContainerInfoService;//spring注入箱信息
    @Autowired
    TbCustomerOrderService tbCustomerOrderService;//spring注入客户订单
    @Autowired
    TbBookingSpaceOrderService tbBookingSpaceOrderService;//spring注入订舱单
    @Autowired
    TbFleetOrderService  tbFleetOrderService;//spring注入车队订单
    @Autowired
    RegionService regionService;


    @Override
    @Transactional
    public String orderInformationSave(OrderInformationVo orderInformationVo){
        SimpleDateFormat fm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        TbCustomerOrder tco = new TbCustomerOrder();
        String res="success";
        boolean spaceOrder=false;//是否生成订仓单
        boolean fleetOrderS=false;//是否生成起始港车队订单
        boolean fleetOrderE=false;//是否生成目的港车队订单
        /**
         * 主要信息
         */
        if(orderInformationVo.getStartFleetPrice()!=null&&(!"".equals(orderInformationVo.getStartFleetPrice()))) {
       //     tco.setStartFleetPriceId(orderInformationVo.getStartFleetPrice());//起始港车队报价
            fleetOrderS=true;//需要生成起始港车队订单
        }
        if(orderInformationVo.getEndFleetPrice()!=null&&(!"".equals(orderInformationVo.getEndFleetPrice()))) {
          //  tco.setEndFleetPriceId(orderInformationVo.getEndFleetPrice());//目的港车队报价
            fleetOrderE=true;//需要生成目的港车队订单
        }
        if(orderInformationVo.getForwardPriceId()!=null&&(!"".equals(orderInformationVo.getForwardPriceId()))) {
          //  tco.setShipPriceId(orderInformationVo.getForwardPriceId());//航线报价
            spaceOrder=true;//需要生成订舱单
        }
        if(orderInformationVo.getXdCompany()!=null&&(!"".equals(orderInformationVo.getXdCompany()))){
            BaseCompany bc = new BaseCompany();//下单公司
            bc.setId(orderInformationVo.getXdCompany());
//            tco.setBaseCompany(bc);
        }


        if(!( fleetOrderS|| fleetOrderE||spaceOrder)){//当报价ID都为空
            return "三类订单至少选一种！";
        }


        if(orderInformationVo.getXdPeople()!=null&&(!"".equals(orderInformationVo.getXdPeople())))
            tco.setOrderUser(orderInformationVo.getXdPeople());//下单人
        if(orderInformationVo.getVoyageId()!=null&&(!"".equals(orderInformationVo.getVoyageId()))) {
            BaseVoyage bv = new BaseVoyage();
                bv.setId(orderInformationVo.getVoyageId());
            tco.setBaseVoya(bv);
        }
        /**
         * 次要信息
         */
        if(orderInformationVo.getTotalPrice()!=null&&(!"".equals(orderInformationVo.getTotalPrice()))){
  //          tco.setTotalPrice(orderInformationVo.getTotalPrice());//货代总价
        }
        if(orderInformationVo.getsName()!=null&&(!"".equals(orderInformationVo.getsName())))
            tco.setConsigneeName(orderInformationVo.getsName());//收货人姓名
        if(orderInformationVo.getsTel()!=null&&(!"".equals(orderInformationVo.getsTel())))
            tco.setConsignee(orderInformationVo.getsTel());//收货人联系方式
        if(orderInformationVo.getsDoorId()!=null&&(!"".equals(orderInformationVo.getsDoorId()))) {
            Region re =new Region();
                re.setCode(orderInformationVo.getsDoorId());
            Region rex = regionService.findOne(re);
            tco.setsDo(rex);//收货门点
        }
        if(orderInformationVo.getfName()!=null&&(!"".equals(orderInformationVo.getfName())))
            tco.setShipperName(orderInformationVo.getfName());//发货人姓名
        if(orderInformationVo.getfTel()!=null&&(!"".equals(orderInformationVo.getfTel())))
            tco.setShipper(orderInformationVo.getfTel());//发货人联系方式
        if(orderInformationVo.getfDoorId()!=null&&(!"".equals(orderInformationVo.getfDoorId()))) {
            Region re =new Region();
                re.setCode(orderInformationVo.getfDoorId());
                Region rex = regionService.findOne(re);
            tco.setfDo(rex);//发货门点
        }
        if(orderInformationVo.getfTime()!=null&&(!"".equals(orderInformationVo.getfTime()))) {//装箱时间
            Date d=null;//String to Date
            try {
                d=ss.parse(orderInformationVo.getfTime());
            } catch (ParseException e) {
                e.printStackTrace();
            }
            if(d!=null)
            tco.setfTime(new DateTime(d));//Date to DateTime
        }
        if (orderInformationVo.getsTime()!=null&&(!"".equals(orderInformationVo.getsTime()))) {//拆卸时间
            Date d=null;//String to Date
            try {
                d=ss.parse(orderInformationVo.getsTime());
            } catch (ParseException e) {
                e.printStackTrace();
            }
            if(d!=null)
            tco.setsTime(new DateTime(d));//Date to DateTime
        }

        tco.setOrdertime(new DateTime());//下单时间
        tco.setFlag("0");//未删除
        tbCustomerOrderService.create(tco);
        /**
         * 箱信息
         */
        JSONArray js= null;
        JSONObject jsq=null;
        int quantity=0;//箱量
        try {
            js = new JSONArray(orderInformationVo.getContainerInfo());
            if(js.length()>0) {
                for(int i=0;i<js.length();i++) {
                    jsq = js.getJSONObject(i);
                    int q=0;
                    if(jsq.getString("quantity")!=null&&(!"".equals(jsq.getString("quantity"))))
                        q = Integer.parseInt(jsq.getString("quantity"));//箱量
                    quantity+=q;//统计箱量
                    if (q > 0) {
                        for (int v = 0; v < q; v++) {//按箱量复制箱
                            TbContainerInfo tci = new TbContainerInfo();
                            tci.setType(jsq.getString("type").toUpperCase());//尺寸类型
                            if (jsq.getString("weight") != null && (!"".equals(jsq.getString("weight"))))
                                tci.setContainerWeight(Float.valueOf(jsq.getString("weight")));//限重
                            if (jsq.getString("volume") != null && (!"".equals(jsq.getString("volume"))))
                                tci.setVolume(Float.valueOf(jsq.getString("volume")));//体积
                            tci.setFlag("0");
                            tci.setTbCustomerOrder(tco);//订单主键
                            tci.setSaveDate(new DateTime());//创建时间
                            tbContainerInfoService.create(tci);//创建
                        }
                    } else {
                        res="error";
                        throw new Exception("箱量异常");//抛出出异常用于回滚

                    }
                }
            }else{
                res="error";
                throw new Exception("没有箱信息");//抛出出异常用于回滚
            }
        } catch (Exception e) {
            res="error";
            e.printStackTrace();
       }

        /**
         * 分支信息生成
         */
        //订舱单
        if(spaceOrder){
            TbBookingSpaceOrder tbso = new TbBookingSpaceOrder();
                tbso.setTbCustomerOrder(tco);//客户订单外键
                tbso.setFlag("0");
                if(orderInformationVo.getForwardPriceTotal()!=null&&(!"".equals(orderInformationVo.getForwardPriceTotal()))) {
   //                 tbso.setTotalPrice(orderInformationVo.getForwardPriceTotal());//总额
                }
                if(orderInformationVo.getForwardCompanyId()!=null&&(!"".equals(orderInformationVo.getForwardCompanyId()))){
                    //货代公司
                    BaseCompany bc= new BaseCompany();
                        bc.setId(orderInformationVo.getForwardCompanyId());
                    tbso.setForwardCompany(bc);
                }
                tbso.setCreateTime(new DateTime());//创建时间
                tbBookingSpaceOrderService.create(tbso);
        }
        //起始港车队订单
        if(fleetOrderS){
            TbFleetOrder tfos =new TbFleetOrder();
                tfos.setTbCustomerOrder(tco);//客户订单外键
                tfos.setFlag("0");
                tfos.setIsStart("0");//是起始港车队
  //              tfos.setCnQuantity(quantity);
                if(orderInformationVo.getStartFleetPriceTotal()!=null&&(!"".equals(orderInformationVo.getStartFleetPriceTotal()))){
                    tfos.setPrice(orderInformationVo.getTotalPrice());//总价
                }
                if(orderInformationVo.getStartFleetCompanyId()!=null&&(!"".equals(orderInformationVo.getStartFleetCompanyId()))){
                    BaseCompany bc  = new BaseCompany();//起始港车队公司
                        bc.setId(orderInformationVo.getStartFleetCompanyId());
                    tfos.setFleetCompany(bc);
                }
                tfos.setCreateTime(new DateTime());//创建时间
                tbFleetOrderService.create(tfos);

        }
        //目的港车队订单
        if(fleetOrderE){
            TbFleetOrder tfoe =new TbFleetOrder();
                tfoe.setTbCustomerOrder(tco);//客户订单外键
                tfoe.setFlag("0");
                tfoe.setIsStart("1");//不是起始港车队
     //           tfoe.setCnQuantity(quantity);
                if(orderInformationVo.getEndFleetPriceTotal()!=null&&(!"".equals(orderInformationVo.getEndFleetPriceTotal()))){
                    tfoe.setPrice(orderInformationVo.getEndFleetPriceTotal());
                }
                if(orderInformationVo.getEndFleetCompanyId()!=null&&(!"".equals(orderInformationVo.getEndFleetCompanyId()))){
                    BaseCompany bc = new BaseCompany();//目的港车队公司
                        bc.setId(orderInformationVo.getEndFleetCompanyId());
                    tfoe.setFleetCompany(bc);
                }
                tfoe.setCreateTime(new DateTime());//创建时间
                tbFleetOrderService.create(tfoe);
        }


        return res;
    }

    @Override
    public String fleetOrderOperate(String orderStatus, String id) {
        TbFleetOrder tfo= tbFleetOrderService.view(id);
        if(tfo!=null){
            tfo.setOrderState(orderStatus);
            tbFleetOrderService.update(tfo);
        }else
            return "error ID";
        return "success";
    }

    @Override
    public String forwardOrderOperate(String orderStatus, String id) {
        TbBookingSpaceOrder tb = tbBookingSpaceOrderService.view(id);
        if(tb!=null){
            tb.setOrderStatus(orderStatus);
            tbBookingSpaceOrderService.update(tb);
        }else
            return "error ID";
        return "success";
    }


}
